package com.nowcoder.community.config;

import com.nowcoder.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.nowcoder.community.util.CommunityConstant.*;

/**
 * @author TwfPlayer
 * @date 2023/8/13 18:14
 * @description: TODO
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 忽略静态资源
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    /**
     * 授权逻辑
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //需要访问权限访问的路径//此处为所有用户登录后访问
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                )
                .hasAnyAuthority(//需要的权限
                        AUTHORITY_USER,AUTHORITY_MODERATOR,AUTHORITY_ADMIN
                )
                .antMatchers(//版主可置顶和加精
                        "/discuss/top",
                        "/discuss/wonderful"
                )
                .hasAnyAuthority(//
                        AUTHORITY_MODERATOR
                )
                .antMatchers(//管理员可拉黑
                        "/discuss/block",
                        "/data/**",
                        "/actuator/**")
                .hasAnyAuthority(
                        AUTHORITY_ADMIN
                )
                .anyRequest().permitAll()  //其他请求均允许
                .and().csrf().disable(); //禁用CSRF防护



        // 权限不足时的处理,认证异常
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {//认证异常处理
                    //未登录
                    @Override
                    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        String xReauestedWith =  httpServletRequest.getHeader("x-requested-with");
                        if("XMLHttpRequest".equals(xReauestedWith)){
                            // 异步请求
                            httpServletResponse.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = httpServletResponse.getWriter();
                            writer.write(CommunityUtil.getJSONString(403,"请先登录!"));
                        }else{
                            //重定向到login
                            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login");
                        }
                    }
                })
                // 权限异常
                .accessDeniedHandler(new AccessDeniedHandler() {//访问权限异常处理
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        String xRequestedWith = httpServletRequest.getHeader("x-requested-with");
                        if("XMLHttpRequest".equals(xRequestedWith)){
                            // 异步请求
                            httpServletResponse.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = httpServletResponse.getWriter();
                            writer.write(CommunityUtil.getJSONString(403,"没有权限访问!"));
                        }else{
                            //重定向到login
                            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/denied");
                        }
                    }
                });

        // Security底层默认拦截"/login"请求,进行退出处理
        // 覆盖它默认的逻辑才能执行项目本身的退出代码
        http.logout().logoutUrl("/securitylogout");

    }

/*    @Override //使用原有的认证逻辑
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }*/
}
